﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KongMing.Common;
using static System.Threading.Thread;
using static System.Console;

namespace Project_5
{
    /// <summary>
    /// 5.4 对连续的异步任务使用await
    /// </summary>
    public class Unit_5_04 : UnitBase
    {
        public static void Go()
        {
            Task t = AsyncWithTPL();
            t.Wait();
            t = AsynchronyWithAwait();
            t.Wait();
        }

        static Task AsyncWithTPL()
        {
            var containerTask = new Task(() =>
              {
                  Task<string> t = GetInfoAsync("TPL 1");
                  t.ContinueWith(task =>
                  {
                      WriteLine(t.Result);
                      Task<string> t2 = GetInfoAsync("TPL 2");
                      t2.ContinueWith(innerTask => WriteLine(innerTask.Result), TaskContinuationOptions.AttachedToParent);
                      t2.ContinueWith(innerTask => WriteLine(innerTask.Exception.InnerExceptions),
                          TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.AttachedToParent);
                  }, TaskContinuationOptions.NotOnFaulted | TaskContinuationOptions.AttachedToParent);
                  t.ContinueWith(task => WriteLine(t.Exception.InnerExceptions),
                      TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.AttachedToParent);
              });

            containerTask.Start();
            return containerTask;
        }

        static async Task AsynchronyWithAwait()
        {
            try
            {
                string result = await GetInfoAsync("Async 1");
                WriteLine(result);
                result = await GetInfoAsync("Async2");
                WriteLine(result);
            }
            catch (Exception e)
            {
                WriteLine(e);
            }
        }


        static async Task<string> GetInfoAsync(string name)
        {
            WriteLine($"Task {name} Started! ");
            await Task.Delay(TimeSpan.FromSeconds(2));
            if (name == "TPL 2")
                throw new Exception("Boom");
            return
                $"Task {name} is running on a thread id {CurrentThread.ManagedThreadId}." +
                $"Is thread pool thread :{CurrentThread.IsThreadPoolThread}";
        }

    }


}
